
package com.jf.cloud.payment.listener;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.jf.cloud.common.order.bo.OrderIdWithRefundIdBO;
import com.jf.cloud.common.order.bo.PayRefundBO;
import com.jf.cloud.common.rocketmq.config.RocketMqConstant;
import com.jf.cloud.payment.model.PayInfo;
import com.jf.cloud.payment.service.PayInfoService;
import com.jf.cloud.payment.service.RefundInfoService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 拼团订单成团失败通知
 * @author zz
 */
@Component
@RocketMQMessageListener(topic = RocketMqConstant.GROUP_ORDER_UN_SUCCESS_REFUND_TOPIC,consumerGroup = RocketMqConstant.GROUP_ORDER_UN_SUCCESS_REFUND_TOPIC)
public class GroupOrderUnSuccessRefundConsumer implements RocketMQListener<List<OrderIdWithRefundIdBO>> {
    private static final Logger log = LoggerFactory.getLogger(GroupOrderUnSuccessRefundConsumer.class);
    @Autowired
    private RefundInfoService refundInfoService;
    @Autowired
    private PayInfoService payInfoService;

    /**
     * 拼团订单成团失败通知
     */
    @Override
    public void onMessage(List<OrderIdWithRefundIdBO> orderIdWithRefundIds) {
        List<Long> orderIds = orderIdWithRefundIds.stream().map(OrderIdWithRefundIdBO::getOrderId).collect(Collectors.toList());
        for (int i = 0; i < orderIds.size(); i++) {
            System.out.println(orderIds.get(i));
            if(ObjectUtil.isEmpty(orderIds.get(i))){
                orderIds.remove(i);
            }
        }
        List<PayInfo> payInfos = payInfoService.listByOrderIds(orderIds);
        if (CollectionUtil.isEmpty(payInfos)) {
            return;
        }
        Map<Long, Long> orderIdWithRefundIdMap = orderIdWithRefundIds.stream().collect(Collectors.toMap(OrderIdWithRefundIdBO::getOrderId, OrderIdWithRefundIdBO::getRefundId));
        for (PayInfo payInfo : payInfos) {
            PayRefundBO payRefundBO = new PayRefundBO();
            payRefundBO.setRefundId(orderIdWithRefundIdMap.get(Long.valueOf(payInfo.getOrderIds())));
            payRefundBO.setRefundAmount(payInfo.getPayAmount());
            payRefundBO.setOrderId(Long.valueOf(payInfo.getOrderIds()));
            payRefundBO.setPayId(payInfo.getPayId());
            payRefundBO.setUnSuccessGroupOrder(1);
            refundInfoService.doRefund(payRefundBO);
        }
    }
}
